package by.amakarevich.dataaccess.Impl;

import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import by.amakarevich.dataaccess.KitDao;
import by.amakarevich.datamodel.Kit;
import by.amakarevich.datamodel.Kit_;
import by.amakarevich.datamodel.Product;


@Repository
public class KitDaoImpl extends AbstractDaoImpl<Long, Kit> implements KitDao{
	protected KitDaoImpl(){
		super(Kit.class);
	}
	
	
	@Override
	public List<Kit> getAllKit(){
        CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

        CriteriaQuery<Kit> criteria = cBuilder.createQuery(Kit.class);
        Root<Kit> root = criteria.from(Kit.class);

        criteria.select(root);
        root.fetch(Kit_.product);
        criteria.distinct(true);
        

        TypedQuery<Kit> query = getEm().createQuery(criteria);
        List<Kit> results = query.getResultList();
        return results;
	}
	 
	public Kit getByProductId(Product product){
		  CriteriaBuilder cBuilder= getEm().getCriteriaBuilder();
		  CriteriaQuery<Kit> criteria=cBuilder.createQuery(Kit.class);
		  Root<Kit> root=criteria.from(Kit.class);
		  
		  criteria.select(root);
	      root.fetch(Kit_.product);
	      criteria.distinct(true);
		  criteria.where(cBuilder.equal(root.get(Kit_.product),product.getId()));

		  TypedQuery<Kit> query = getEm().createQuery(criteria);
	      Kit results = (Kit)query.getSingleResult();
	      return results;
	}
	
}
